#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/12/13
# @Author :songtx
# @File   :i2c.py


import time
import numpy as np
from smbus import SMBus


def i2c():
    global level_5
    for m in range(4):  # 每次执行一次，读取4个当前液位
        level_init[m, 0] = bus.read_word_data(dict3[m], 0x00)
    level_5 = np.hstack((level_init, level_5))  # 左边插入一组新值
    level_5 = np.delete(level_5, -1, 1)         # 右边抛弃一组旧值
    alarm_high = level_5.mean(axis=1) > level_high
    alarm_low = level_5.mean(axis=1) < level_low
    level = np.vstack((level_5.mean(axis=1), np.vstack((alarm_high, alarm_low)))).T
    return level


if __name__ == "__main__":
    bus = SMBus(1)      # 创建接口
    level_high = 200    # 高液位报警限值
    level_low = 50      # 低液位报警限值
    level_init = np.zeros(4).reshape(4, 1)   # 创建一个空数组
    level_5 = np.empty(shape=(4, 0))
    dict3 = {0: 0x40, 1: 0x41, 2: 0x42, 3: 0x43}
    for i in range(10):      # 初始化执行一次，预读5个值,修改持值可直接修改预读数量
        for j in range(4):
            level_init[j, 0] = bus.read_word_data(dict3[j], 0x00)
        level_5 = np.hstack((level_init, level_5))
        time.sleep(0.25)
    for k in range(100):
        print(i2c())
        time.sleep(1)
